/**
* File Name: daemon.c
* Auther: Jichang
* Environment: Fedora 7 server
* daemon process
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>

void sys_err(const char *str) 
{
	perror(str);
	exit(1);
}

int main(int argc, char *argv[])
{
	pid_t pid;
	int ret, fd;

	pid = fork();
	if(pid > 0) {
		// father end.
		exit(0);
	}
	pid = setsid();  // create new session.
	if(pid == -1) {
		sys_err("setsid error");
	}

	ret = chdir("./");  // change path.
	if(ret == -1) {
		sys_err("chdir error");
	}

	umask(0022);  // change file visit-mask.

	// redirect.
	close(STDIN_FILENO); // close file descriptor 0
	fd = open("/dev/null", O_RDWR); // fd -> 0
	if(fd == -1) {
		sys_err("open error");
	}

	dup2(fd, STDOUT_FILENO); 
	dup2(fd, STDERR_FILENO);

	while(1);  // simulate logic.
	
	return 0;
}

